package weeny.pre.io.parser;

import prefuse.data.parser.DataParseException;
import prefuse.data.parser.DataParser;
import prefuse.data.parser.IntArrayParser;
import prefuse.util.ColorLib;

/**
 * Breaking an interger into r,g,b,a components, showing it as an integer array.
 * Handle a single integer as "rrrrrrrrggggggggbbbbbbbbaaaaaaaa", or an integer
 * array with four elements as [r, g, b, a]
 * 
 * @author weeny
 */
public class ColorParser implements DataParser{
	public boolean canParse(String text) {
		try {
			parse(text);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	public boolean compatible(Class type) {
		return type == int.class || type == Integer.class;
	}

	private static int[] temp = new int[4];
	private static IntArrayParser iaParser = new IntArrayParser();
	public String format(Object value) {
		if (value == null) {
			return "";
		}
		int c = ((Number) value).intValue();
		temp[0] = ColorLib.red(c);
		temp[1] = ColorLib.green(c);
		temp[2] = ColorLib.blue(c);
		temp[3] = ColorLib.alpha(c);
		return iaParser.format(temp);
	}

	public Class getType() {
		return int.class;
	}

	public Object parse(String text) throws DataParseException {
		try{
			int[] val = (int[]) iaParser.parse(text);
			if (val.length == 1) {
				return val[0];
			}
			else {
				return ColorLib.rgba(val[0], val[1], val[2], val[3]);
			}
		}
		catch (Exception e) {
			throw new DataParseException("Color is wrong");
		}
	}
}